package com.framework.component.resolver.handlebars;

import com.framework.component.resolver.exception.ResolverException;
import com.framework.component.resolver.model.BusinessModel;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.ValueResolver;
import com.github.jknack.handlebars.context.MapValueResolver;
import lombok.Getter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Getter
@Component
public class HandlebarsHelper {

    private final Handlebars handlebars;

    private final HandlebarsValueResolver handlebarsValueResolver;

    public HandlebarsHelper(HandlebarsValueResolver handlebarsValueResolver) {
        this.handlebarsValueResolver = handlebarsValueResolver;
        handlebars = new Handlebars();
        handlebars.registerHelpers(DefaultHelper.class);
    }

    public String compileAndApply(String location, BusinessModel model) {
        try {
            Context context = Context.newBuilder(model)
                    .resolver(resolvers())
                    .build();
            Template template = this.handlebars.compile(location);
            return template.apply(context);
        } catch (Exception e) {
            throw new ResolverException("handlebars compile error for location:" + location, e);
        }
    }

    private ValueResolver[] resolvers() {
        List<ValueResolver> valueResolvers = new ArrayList<>();
        valueResolvers.add(handlebarsValueResolver);
        valueResolvers.add(MapValueResolver.INSTANCE);
        return valueResolvers.toArray(new ValueResolver[0]);
    }
}
